<template>
    <view class="pageconfig">
        <view @click="goTomian" class="flex1 response flex">
            <view class="flex2 flex">
                <text class="text3 text-white">编号</text>
                <text class="text4 text-white">{{ id }}</text>
            </view>
     <view @click="goToWifiDetails" class="flex5 flex" style="flex-direction: column;">
       <text class="text6 text-white"></text>
       <text class="text7 text-white">{{ currentWifi }}</text>
       <text class="text7 text-white">level {{ wifiSignalStrength }}</text>

     </view>
		<view @click="goToudp" class="flex8 flex">
			<text  class="text9 text-white">{{ serverIp }}连接</text>
			
		</view>
    </view>
        <view class="flex10 response flex">
            <view class="flex11 flex">
                <text @click="goTomanual" class="text12 text-white"  :style="{ position: 'absolute', top: '12%', left: '10%' }">自动模式</text>
                <text class="text13 text-white" :style="{ position: 'absolute', top: '15%', left: '10%' }">当前模式：{{ mode }}</text>
                <text class="text14 text-white" :style="{ position: 'absolute', top: '18%', left: '10%' }">目标速度：{{ msginfo && msginfo.speed !== undefined ? msginfo.speed + '  m/s' : 'none' }}</text>
                <text class="text15 text-white" :style="{ position: 'absolute', top: '21%', left: '10%' }">温度：{{ msginfo && msginfo.tem !== undefined ? msginfo.tem + ' ℃' : 'none' }}</text>
                <text class="text16 text-white" :style="{ position: 'absolute', top: '24%', left: '10%' }">电量：{{ msginfo && msginfo.bLevel !== undefined ? msginfo.bLevel + ' %' : 'none' }}</text>
                <text class="text17 text-white" :style="{ position: 'absolute', top: '27%', left: '10%' }">位置：{{ msginfo && msginfo.x !== undefined ? msginfo.x + ' m' : 'none' }},{{ msginfo && msginfo.y !== undefined ? msginfo.y + ' m' : 'none' }}</text>
				<text class="text16 text-white" :style="{ position: 'absolute', top: '27%', left: '45%' }">实际速度：{{ msginfo && msginfo.v !== undefined ? msginfo.v + ' m/s' : 'none' }}</text>
				<text class="text16 text-white" :style="{ position: 'absolute', top: '18%', left: '45%' }">倾角：{{ msginfo && msginfo.a !== undefined ? msginfo.a + ' rad' : 'none' }}</text>
				<text class="text16 text-white" :style="{ position: 'absolute', top: '21%', left: '45%' }">转角：{{ msginfo && msginfo.d !== undefined ? msginfo.d + ' rad' : 'none' }}</text>
				<text class="text15 text-white" :style="{ position: 'absolute', top: '24%', left: '45%' }">里程：{{ msginfo && msginfo.s !== undefined ? msginfo.s + '  m' : 'none' }}</text>

				<div>
				<div :style="{ position: 'absolute', top: '15%', left: '76%', display: 'flex', alignItems: 'center' }">
				  <text class="text text-white">电机</text>
				  <div :style="{ ...getCircleStyle(status.motor), marginLeft: '5px' }"></div>
				</div>

				<div :style="{ position: 'absolute', top: '18%', left: '76%', display: 'flex', alignItems: 'center' }">
				  <text class="text text-white">气泵</text>
				  <div :style="{ ...getCircleStyle(status.pump), marginLeft: '5px' }"></div>
				</div>

				<div :style="{ position: 'absolute', top: '21%', left: '76%', display: 'flex', alignItems: 'center' }">
				  <text class="text text-white">阀门</text>
				  <div :style="{ ...getCircleStyle(status.valve), marginLeft: '5px' }"></div>
				</div>

				<div :style="{ position: 'absolute', top: '24%', left: '76%', display: 'flex', alignItems: 'center' }">
				  <text class="text text-white">滚刷</text>
				  <div :style="{ ...getCircleStyle(status.brush), marginLeft: '5px' }"></div>
				</div>

				<div :style="{ position: 'absolute', top: '27%', left: '76%', display: 'flex', alignItems: 'center' }">
				  <text class="text text-white">舵机</text>
				  <div :style="{ ...getCircleStyle(status.servo), marginLeft: '5px' }"></div>
				</div>
				</div>
            </view>
        </view>
        <view class="flex18 response flex">
            <view class="flex19    flex   ">
                <text class="text20 text-white ":style="{ position: 'absolute', top: '35%', left: '3%' }"> 轨迹选择：</text>
                <text class="text21 text-white ":style="{ position: 'absolute', top: '50%', left: '8%' }"> 边缘灵敏度：</text>
                <text class="text22 text-white ":style="{ position: 'absolute', top: '60%', left: '8%' }"> 充电阈值：</text>
   <view class="cu-form-group" >
	   <slider style="width: 70%; position: absolute; top: 53%; left: 15%; " :value="value2" :min="min" :max="max" :step="step" :active-color="activeColor" 
			   :background-color="backgroundColor" :show-value="showValue" @change="sliderChange1" :value-style="{ color: 'white !important'}">  
	   </slider>
   </view>
   <view class="cu-form-group ">
	   <slider style="width: 70%; position: absolute; top: 63%; left: 15%; opacity: 1;" 
			   :value="value2" :min="min" :max="max" :step="step" :active-color="activeColor" :background-color="backgroundColor" 
			   :show-value="showValue" @change="sliderChange2"></slider>
   </view>
   <view class="content ">  
	   <downSelect ref='selectRef' :style="{ position: 'absolute', top: '40%', left: '26%' }" showKey="name" mode='single' :dataList="list" @resultBack="result">
		   <view class="select-btn" @click="handleClick" >选择路径</view> 
	   </downSelect>
	   <view :style="{ position: 'absolute', top: '40.3%', left: '80%', color: 'white' }">{{select.name}}</view>  
   </view>
        </view>
        </view>
		<view class="jsonmsg-display">
		  <text>jsonmsg: {{ JSON.stringify(jsonmsgContent, null, 2) }}</text>
		</view>
    </view>
	
</template>

<script>
import downSelect from "@/components/down-select.vue"
import { mapState, mapActions } from 'vuex';
export default {
	components: {
				downSelect
			},
    data() {
        return {
		select: {},
			list: [{name: 'A'}, 
				   {name: 'B'}, 
				   {name: 'C'}],
			min: 1,
			showValue: true,
            jsonmsgContent: '', 
	        jsonString: '',
			step: 1,
			value2: 71,
			      status: {
			        motor: null, 
			        pump: null, 
			        valve: null, 
			        brush: null, 
			        servo: null, 
			      },
			msginfo: null ,
			msgAT: null ,
			      sensitivity: 0, // 对应 sliderChange1 的值
			      threshold: 0,   // 对应 sliderChange2 的值
			      presetPath: '' , // 对应 result 的值
			max: 100,
			activeColor: '#00aa00',
			backgroundColor: '#c8c8c8',
			value2: 71,
			rangindex3: 0,
			selectedValue3: '',
            socketPort: 9091,
            udpClient: null,
            id: '',
            ip: '',
            speed: 0,
            mode: '',
            sensitivity: 0.8,
            threshold: 20,
            activeColor: '#00aa00',
            backgroundColor: '#eee',
            wifiSignalStrength: 0,
            currentIp: '192.168.0.169',
            newIp: '192.168.0.169',
            currentWifi: 'none',
            receivedMessages: []  
        };
    },
	computed: {
	...mapState({
	  udpMessages: state => state.udpMessages, 
	  serverIp: state => state.serverIp,
	}),
	},
  mounted() {
    if (this.msginfo) {
      this.updateStatusFromMsgInfo();
    } else {
      console.info("wait msginfo");
    }
  },
	watch: {
		    msginfo: {
		      handler() {
		        this.updateStatusFromMsgInfo();
		      },
		      deep: true,
		    },
		  udpMessages: {
		        handler(newMessages) {
		          this.jsonmsgContent = newMessages.length ? newMessages[newMessages.length - 1] : '';
				  this.processJsonMsg(); 
				  
		        },
		        deep: true,
		        immediate: true, 
		      },
			  jsonmsgContent: { 
			      handler(newContent) {
			        if (newContent) {
			          this.processJsonMsg(); 
			        }
			      },
			      immediate: true,
			    },
		},
			  
    onLoad(options) {
        if (options && options.id) {
            this.id = options.id;
        }

        if (options && options.newIp) {
            this.newIp = options.newIp ? options.newIp : this.currentIp;
        } else {
            this.newIp = this.currentIp;
        }

        this.startWifi();
    },
    methods: {
		...mapActions([
		  'updateServerIp',
		]),
		updateStatusFromMsgInfo() {
		        if (this.msginfo) {
		          this.status.motor = this.msginfo.motor;
		          this.status.pump = this.msginfo.pump;
		          this.status.valve = this.msginfo.valve;
		          this.status.brush = this.msginfo.brush;
		          this.status.servo = this.msginfo.servo; 
		        }
		},
		    getCircleStyle(value) {
		      let color;
		      if (value === 0) {
		        color = 'red';
		      } else if (value === 1 || value === 255) { // servo can have 255 for green
		        color = 'green';
		      } else if (value === null || value === undefined) {
		        color = 'gray';
		      } else {
		        color = 'yellow';
		      }
		      return {
		        width: '10px',
		        height: '10px',
		        backgroundColor: color,
		        borderRadius: '50%',
		        display: 'inline-block',
		      };
		    },
			result(result) {
						this.select = result[0]
					this.presetPath = this.select; // 或者根据你的数据结构选择合适的字段
					      this.sendAutoCommand(this.presetPath, this.sensitivity, this.threshold);
					    },
					handleClick() {
						this.$refs.selectRef.open()
					},
		        handleSelectChange() {
		            this.showSlider = false;
		        },
		        sliderChange24(value) {
		            // 滑块改变时的逻辑
		            console.log("Slider Value:", value);
		        },
				async processJsonMsg() {
				  // 将 jsonmsgContent 转换为字符串
				  const jsonString = JSON.stringify(this.jsonmsgContent, null, 2);
				  this.jsonString = jsonString; 
				  const parsedContent = JSON.parse(jsonString); // 解析为对象
				    if (parsedContent.msg) {
				      const msgContent = JSON.parse(parsedContent.msg); 
					  const msginfo = msgContent.info; 
					    this.msginfo = msginfo;
					  const msgAT = msgContent.AT; 
					    this.msgAT = msgAT;
					  } 
				  },
				  
        startWifi() {
            uni.startWifi({
                success: () => {
                    this.getConnectedWifi();
                },
                fail: (err) => {
                    console.error("启动 WiFi 模块失败:", err);
                }
            });
        },
        getConnectedWifi() {
            if (typeof uni.getConnectedWifi === 'function') {
                uni.getConnectedWifi({
                    success: (res) => {
                        if (res.wifi) {
                            this.currentWifi = res.wifi.SSID;
                            this.wifiSignalStrength = this.calculateWifiSignalLevel(res.wifi.signalStrength);
                        }
                    },
                    fail: (err) => {
                        console.error("获取 WiFi 连接失败:", err);
                    }
                });
            } else {
                console.error("WiFi 功能未初始化或不可用");
            }
        },
        calculateWifiSignalLevel(signalStrength) {
            const levels = 5;
            const maxSignal = -30;  // 最大信号强度 (dBm)
            const minSignal = -100; // 最小信号强度 (dBm)
            if (signalStrength <= minSignal) {
                return 0;
            } else if (signalStrength >= maxSignal) {
                return levels;
            } else {
                return Math.round((signalStrength - minSignal) * levels / (maxSignal - minSignal));
            }
        },
        sendCommand(command) {
            const jsonMessage = {
                manual: {
                    directionControl: command
                }
            };
            this.$store.commit('sendmsg',jsonMessage)
        },
		sliderChange1(value) {
		      this.sensitivity = value;
		      this.sendAutoCommand(this.presetPath, this.sensitivity, this.threshold);
		    },
		    sliderChange2(value) {
		      this.threshold = value;
		      this.sendAutoCommand(this.presetPath, this.sensitivity, this.threshold);
		    },
        goTomanual() {
            uni.navigateTo({
                url: `/pages/index/manual?id=${this.id}`
            });
        },
        goTomian() {
            uni.switchTab({
                url: `/pages/index/index`
            });
        },
        goToWifiDetails() {
            uni.switchTab({
                url: `/pages/index/wifiDetails?id=${this.id}`
            });
        },
		goToudp() {
            uni.switchTab({
                url: `/pages/index/server?id=${this.id}`
            });
        },
         onSelected(event) {
                    const selectedPath = this.pathOptions[event.detail.value]; // 获取选中的路径
                    console.log("选择的路径: ", selectedPath);
                    this.sendAutoCommand(selectedPath, this.sensitivity, this.threshold);
                },
        sliderChange24(e) {
            this.sensitivity = e.detail.value;
            this.sendAutoCommand(this.defaultmenulist23[0][this.defaultIndex23[0]].value, this.sensitivity, this.threshold);
        },
        sliderChange25(e) {
            this.threshold = e.detail.value;
            this.sendAutoCommand(this.defaultmenulist23[0][this.defaultIndex23[0]].value, this.sensitivity, this.threshold);
        },
        sendAutoCommand(presetPath, sensitivity, threshold) {
            const jsonMessage = {
                AT: {
                    otMode: "NN",
                    Path: presetPath.name,
                    tivity: sensitivity,
                    TH: threshold
                }
            };
            this.$store.commit('sendmsg',jsonMessage)
        }
    },
	  props: {
	    
	  },
    onUnload() {
        // 释放 socket，释放端口
        if (this.udpClient) {
            this.udpClient.release();
        }
    }
}
</script>



<style lang="less">
    .pageconfig {
        width: 100%;
        overflow: hidden;
        overflow-y: scroll;
        height: 100%; 
    }
.cu-form-group {
           width: 100%;
           
       }

.select-btn {
		width: 380rpx;
		height: 60rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		border: 30rpx solid #e5e5e5;
		border-radius: 15rpx;
	}
    /**pagedomcss**/

.white-background {
        background-color: white;
    }
    .flex1 {
        width: 100%;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
		overflow-y: auto; /* 启用滚动，只在需要的容器中 */
		box-sizing: border-box; /* 避免宽度溢出 */
    }

    .flex2 {
        width: 26%;
        height: 120rpx;
        background-color: rgba(45, 140, 240, 1);
        margin-left: 30rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
    }

    .text3 {
        margin-left: 30rpx;
    }

    .text4 {
        margin-top: 50rpx;
        margin-bottom: 16rpx;
        margin-left: -16rpx;
    }

    .flex5 {
        width: 28%;
        height: 120rpx;
        background-color: rgba(45, 140, 240, 1);
        margin-left: 30rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
    }

    .text6 {
        margin-left: 34rpx;
    }

    .text7 {
		font-size: 10px; 
        margin-top: 20rpx;
        margin-left: 20rpx;
    }

    .flex8 {
        width: 27%;
        height: 120rpx;
        background-color: rgba(45, 140, 240, 1);
        margin-left: 30rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
    }

    .text9 {
        margin-top: 36rpx;
        margin-left: 10rpx;
    }

    .flex10 {
        width: 100%;
        height: 400rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
		overflow-y: auto; /* 启用滚动，只在需要的容器中 */
		box-sizing: border-box; /* 避免宽度溢出 */
    }

    .flex11 {
        width: 87%;
        height: 320rpx;
        background-color: rgba(45, 140, 240, 1);
        margin-top: 32rpx;
        margin-left: 36rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
    }

    .text12 {
        width: 38%;
        font-weight: 600;
    }

   
    .text14 {

    }

    .text15 {

    }

    .text16 {

    }

    .text17 {

    }

    .flex18 {
        width: 100%;
        height: 600rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
		overflow-y: auto; /* 启用滚动，只在需要的容器中 */
		box-sizing: border-box; /* 避免宽度溢出 */
    }

    .flex19 {
        width: 87%;
        height: 520rpx;
        background-color: rgba(45, 140, 240, 1);
        margin-top: 32rpx;
        margin-left: 36rpx;
        align-items: flex-start;
		border-radius: 5px; /* 添加圆角 */
    }

    .text20 {
        width: 38%;
        margin-top: 74rpx;
        font-weight: 600;
        text-indent: 30rpx;
    }

  

    .dropmenu23 {
        width: 20%;
        margin-top: 128rpx;
        margin-left: 3rpx;
    }

    /**本页滑块控件24的css代码**/
    .commoncss24 {
        width: 58%;
        background-color: #ffffff;
        margin-top: 260rpx;
        margin-left: -184rpx;
    }

    /**本页滑块控件25的css代码**/
    .commoncss25 {
        width: 59%;
        background-color: #ffffff;
        margin-top: 408rpx;
        margin-left: -380rpx;
    }
	/* 样式可以根据需要自行调整 */
  /* 样式可以根据需要自行调整 */
  .received-messages {
    margin-top: 20px;
    padding: 10px;
    background-color: rgba(255, 255, 255, 0.8);
    position: fixed;
    bottom: 0;
    width: 100%;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  }

  .received-message {
    padding: 5px;
    background-color: #f0f0f0;
    margin-bottom: 5px;
  }

</style>
